package com.dashunzi.yueyutianqi.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2016/4/9 0009.
 * 作者：大顺子
 */
public class HttpUtil {
    public static void sendHttpRequest(final String address, final HttpCallbackListener httpCallbackListener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(address);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    InputStream is = conn.getInputStream();
                    BufferedReader bis = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bis.readLine()) != null) {
                        sb.append(line);
                    }
                    if (httpCallbackListener != null) {
                        httpCallbackListener.onFinish(sb.toString());
                    }
                } catch (Exception e) {
                    if (httpCallbackListener != null) {
                        httpCallbackListener.onError(e);
                    }

                } finally {
                    //关闭连接
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();

    }
}
